import java.util.Arrays;


//归并排序
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = new int[8000000];
        for (int i = 0; i < 8000000; i++) {
            arr[i] = (int) (Math.random() * 80000);
        }
        //System.out.println(Arrays.toString(arr));
        int[] temp = new int[arr.length];
        long start = System.currentTimeMillis();
        mergeSort(arr, 0, arr.length - 1, temp);
        //System.out.println(Arrays.toString(arr));
        long end = System.currentTimeMillis();
        System.out.println(end - start);  //1359  ,归并排序800万个随机数据的数组需要的ms数
    }


    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            //合并
            merge(arr, left, mid, right, temp);
        }
    }

    //合并方法
    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int t = 0; //指向temp数组的当前索引

        //比较左右俩个有序序列的大小
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t++] = arr[i++];
            } else {
                temp[t++] = arr[j++];
            }
        }
        //比较完之后填充
        while (i <= mid) {
            temp[t++] = arr[i++];
        }
        //比较完之后填充
        while (j <= right) {
            temp[t++] = arr[j++];
        }


        //拷贝数组
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            arr[tempLeft++] = temp[t++];
        }
    }
}
